import router from "@/router";
import { RouteLocationNormalized } from "vue-router";
import { getToken } from "@/utils/auth";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style

NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList: Array<string> = ["/login","/404","/500"];
router.beforeEach(
	async (
		to: RouteLocationNormalized,
		_: RouteLocationNormalized,
		next: any
	) => {
		// start progress bar
		NProgress.start();
		// Determine whether the user has logged in
		const token = getToken();
		if (token) {
			if (to.path === "/login") {
				// If is logged in, redirect to the home page
				next({ path: "/" });
				NProgress.done()
			} else {
				next();
				NProgress.done()
			}
		} else {
			if (whiteList.indexOf(to.path) !== -1) {
				next();
				NProgress.done()
			} else {
				next(`/login?redirect=${to.path}`);
				NProgress.done()
			}
		}
	}
);
router.afterEach((to: RouteLocationNormalized) => {
	if (typeof to.meta.title === "string") {
		document["title"] = to.meta.title;
	}
	NProgress.done()
});
